package com.test.demo.provider.service.impl;


import com.test.demo.provider.service.DemoService;
import com.test.demo.provider.service.DemoServiceListener;
import org.apache.dubbo.config.annotation.Argument;
import org.apache.dubbo.config.annotation.Method;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Value;

import java.time.LocalDateTime;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

//客户端传一个监听器，服务端执行后去回调客户端监听器中的方法，如何回调可自定义
//版本                                                    方法                                     第二个参数设置为回调           最多的回调个数
//@Service(version = "callback",methods = {@Method(name = "sayHello",arguments = {@Argument(index = 1,callback = true)})},callbacks = 3)
public class CallbackDemoServiceImpl implements DemoService {
    private final ConcurrentHashMap<String,DemoServiceListener> listeners= new ConcurrentHashMap();

    @Value("${server.port}")
    private Integer port;
    @Override
    public String sayHello(String msg) {
        System.out.println("Hello "+msg+port);
        return "Hello "+msg+port;
    }

    public CallbackDemoServiceImpl() {
        Thread t = new Thread(new Runnable() {
            public void run() {
                while(true) {
                    try {
                        //只执行一次回调
                        Iterator<Map.Entry<String, DemoServiceListener>> iterator = listeners.entrySet().iterator();
                        while (iterator.hasNext()){
                            Map.Entry<String, DemoServiceListener> entry = iterator.next();
                            try {
                                entry.getValue().changed(getChanged(entry.getKey()));
                            } catch (Throwable t) {

                            }finally {
                                listeners.remove(entry.getKey());
                            }
                        }
                        Thread.sleep(1000); // 定时触发变更通知

                    } catch (Throwable t) { // 防御容错
                        t.printStackTrace();
                    }
                }
            }
        });
        t.setDaemon(true);
        t.start();
    }

    @Override
    public String sayHello(String msg, DemoServiceListener demoServiceListener) {
        String key="Hello "+msg+port;
        listeners.put(key,demoServiceListener);
        return getChanged(key);
    }

    private String getChanged(String key) {
        return "Changed: " + LocalDateTime.now().toString()+key;
    }

}
